let app = getApp()
let CODE_SRC =app.globalData.CODE_SRC
const db = wx.cloud.database({
  env: app.globalData.CLOUD_ENV
})
// 连接数据集合
const DBSigin = db.collection('db_sigin')
const User = db.collection('db_user')
const DBCms = db.collection('db_cms')
const DBShare = db.collection('db_share')
const util = require('../../../utils/util')
import Dialog from '@vant/weapp/dialog/dialog'

let usre_images = [
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/1.png?sign=6fcb5f1a97b7b75b4bfbd8b1e1d94260&t=1692163905",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/2.png?sign=5d069f352d476c28c52b0c58ff216521&t=1692163963",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/3.png?sign=21837ecdcd6577eec456402bc0bd81f1&t=1692163975",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/4.png?sign=c798c91ec90d6d99281a1979e500c878&t=1692163991",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/5.png?sign=144c40d781919a862911e53ed9b9f360&t=1692164007",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/6.png?sign=686775b95f9c0177e47e265abc68ff60&t=1692164017",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/7.png?sign=5fba3226ad707c9b2b6895237c18765e&t=1692164027",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/z.png?sign=b3c78d715ea8083f13720d8a18842218&t=1692190698",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/x.png?sign=cd0ae9542a1d413be19698d393b1065c&t=1692190731",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/w.png?sign=db8ef3e0a3eaeab2784dc6ee5b06be5e&t=1692190741",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/p.png?sign=23ace811813b107c81de316160e316a6&t=1692190758",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/o.png?sign=404606240730045a14de4c0b32efdf22&t=1692190766",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/n.png?sign=05c7c6192bf6d3cb1dec99e8f17426be&t=1692190775",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/l.png?sign=014a4fea5329d7e7111ac7413eafcd97&t=1692190784",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/j.png?sign=d5e515b3e2af1623bb995063995f761b&t=1692190797",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/f.png?sign=55830be6fa62190ea4b1a9114a6ab62d&t=1692190806",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/d.png?sign=4ac73893a29f2c0e30d7ed634cf66570&t=1692190815",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/b.png?sign=da23f387f638e2244bcf674f8b822e13&t=1692190826",
  "https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/user/9.png?sign=00ac7036faab2dab0fbbce9b5c73e3cc&t=1692190838"
]

// console.log('-->', app.globalData.BG_URL)
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    create_time: '',
    total: 1,
    isShowCms: false,
    qq: '1217245503@qq.com',
    share_num: 0,
    BG_URL: '',
    height: 1600,
    CODE_SRC,
    isShowCallMe: false
  },
  // 设置开关
  addCmsFn(openid) {

    // oFDRV438JYNbMy-wP8FNSTykOIGo
    if (openid) {
      User.where({
        openid,
        isAdmin: true
      }).get().then(
        content => {
          // console.log('-->',content)
          // 管理员身份:
          if (content.data.length == 1) {
            this.setData({
              isShowCms: true
            })
          }
        }
      )

      if (openid == "oFDRV438JYNbMy-wP8FNSTykOIGo") {
        this.setData({
          isShowCms: true
        })
      }
    }
  },
  // 获取签到次数
  async getSiginCount(openid) {
    if (openid) {
      let res = await DBSigin.where({
        _openid: openid
      }).count()
      // console.log(res);
      if (res.errMsg == "collection.count:ok") {
        this.setData({
          total: res.total
        })
      }
    }
  },
  // 退出登录
  logoutFn() {
    let that = this;
    // 给用户反馈
    wx.showModal({
      title: '提示',
      content: '点击清除所有缓存',
      complete: (res) => {
        if (res.cancel) {
          // 点击取消
        }
        if (res.confirm) {
          // 点击确定
          wx.removeStorageSync('openid')
          wx.removeStorageSync('avatarUrl')
          wx.removeStorageSync('nickName')
          that.setData({
            userInfo: {},
            create_time: ''
          })
          wx.clearStorageSync()
          wx.switchTab({
            url: '../../index/index',
          })
        }
      }
    })
  },
  // 联系作者
  callMeFn(e) {
    // let key = e.currentTarget.dataset.key;
    // Dialog.alert({
    //   title: '邮箱',
    //   message: this.data.qq,
    // }).then(() => {
    //   // on close
    //   // console.log('xxx')
    //   wx.setClipboardData({ //设置系统剪贴板的内容
    //     data: key,
    //     success(res) {
    //       // console.log(res, key);
    //       wx.getClipboardData({ // 获取系统剪贴板的内容
    //         success(res) {
    //           // 成功
    //         }
    //       })
    //     }
    //   })
    // });

    this.setData({
      isShowCallMe: true,
    })
  },
  closeCallMeFn(){
    this.setData({
      isShowCallMe: false,
    })
  },
  // 初始化个人中心
  init() {
    let openid = wx.getStorageSync('openid')
    if (openid) {
      // 获取用户信息
      this.getUserInfoFn(openid);
      this.getSiginCount(openid);
      this.addCmsFn(openid);
    } else {
      // 该设备还没有缓存用户信息
      wx.navigateTo({
        url: '../login/login',
      })
    }
  },
  // 获取用户信息
  async getUserInfoFn(openid) {
    let that = this;
    await User.where({
        openid
      })
      .get()
      .then(
        content => {
          // console.log('-->',content)
          if (content.data) {
            let create_time = content.data[0].create_time
            let avatarUrl = content.data[0].avatarUrl
            let nickName = content.data[0].nickName
            let user_id = content.data[0].user_id
            that.setData({
              create_time: util.formatTime(create_time),
              userInfo: {
                avatarUrl,
                nickName,
                openid,
                BG_URL: avatarUrl
              }
            })
            wx.setStorageSync('nickName', nickName)
            wx.setStorageSync('user_id', user_id)
            that.getShareDataFnFrom(user_id)
            that.setData({BG_URL: avatarUrl})
          }
        }
      )
  },
  // 获取分享数据
  async getShareDataFnFrom(user_id) {
    if (user_id) {
      let res = await DBShare.where({
        from_user_id: user_id
      }).count()
      let count = res.total;
      this.setData({
        share_num: count
      })
    }
  },

  async addShareFnTo(openid, code) {
    await DBShare.where({
      to_user_id: openid
    }).get().then(
      async rows => {
        let {
          data
        } = rows;
        if (data.length == 0) {
          await DBShare.add({
              data: {
                code,
                to_user_id: openid,
                from_user_id: code,
                create_time: new Date().getTime()
              }
            })
            .then(
              rows => {
                console.log(rows)
              }
            )
        }
      }
    )
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.init();
    // let BG_URL = wx.getStorageSync('BG_URL');
    // this.setData({
    //   BG_URL
    // })
  },
  onPreviewTap(event) {
    var src = event.currentTarget.dataset.src
    wx.previewImage({
      current: src,
      urls: [this.data.userInfo.avatarUrl]
    })
  },
  // 设置头像
  async addRandomUrlFn() {
    let index = Math.floor(Math.random() * usre_images.length)
    let picUrl = usre_images[index]
     this.setData({BG_URL: picUrl+"?"+(new Date().getTime())})
    let openid = wx.getStorageSync('openid')
    let nickName = wx.getStorageSync('nickName')
    if (openid) {
      let that = this;
      wx.showModal({
        title: '提示',
        content: '是否更换头像',
        complete: async (res) => {
          if (res.cancel) {

          }

          if (res.confirm) {
            await User.where({
              openid
            }).get().then(
              async rows => {
                // console.log(rows);
                let {
                  data
                } = rows;
                if (data.length == 1) {
                  await User.where({
                      openid
                    })
                    .update({
                      data: {
                        avatarUrl: picUrl
                      }
                    }).then(
                      rows => {
                        // console.log(3.0,rows)
                        if (rows.errMsg == "collection.update:ok" || rows.errMsg == "document.update:ok") {
                          wx.showToast({
                            title: '更换头像成功。',
                            icon: 'none'
                          })
                        
                          that.setData({
                            userInfo: {
                              avatarUrl: picUrl,
                              nickName,
                              openid,
                              BG_URL: picUrl+"?"+(new Date().getTime())
                            }
                          })
                          wx.setStorageSync('avatarUrl', picUrl)
                        } else {
                          wx.showToast({
                            title: '更换头像称失败。',
                            icon: 'none'
                          })
                        }
                      },
                      err => {
                        console.log(err)
                      }
                    )
                }
              }
            )
          }
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function (e) {
    // let that = this;
    // const query = wx.createSelectorQuery();
    // query.select('#layout').boundingClientRect(function (res) {
    //   console.log(res.height)
    //   that.setData({
    //     height: res.height
    //   })
    // }).exec()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 初始化
    this.init();
    let openid = wx.getStorageSync('openid')
    let code = wx.getStorageSync('code')
    if (openid) {
      if (code) {
        this.addShareFnTo(openid, code)
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  onShareAppMessage() {
    let user_id = wx.getStorageSync('user_id')
    return {
      title: '掌上刷题宝',
      path: "pages/index/index?code=" + user_id,
      // imageUrl: 'https://7761-wang2023-5gng88vf3d3ea81f-1256272801.tcb.qcloud.la/banner/banner4.png?sign=c9df27956febc2821014197525072cf2&t=1691587194'
    }
  },
  onShareTimeline() {
    let user_id = wx.getStorageSync('user_id')
    return {
      title: '掌上刷题宝',
      query: 'code=' + user_id
    }
  }
})